package com.ruoyi.framework.aspectj;

import com.ruoyi.common.annotation.EventTracking;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.domain.SysEventTracking;
import com.ruoyi.system.service.ISysEventTrackingService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class EventTrackingAspect {

    @Autowired
    private ISysEventTrackingService eventTrackingService;
    @Autowired
    private RedisCache redisCache;

    @Around("@annotation(eventTracking)")
    public Object jointPotin(ProceedingJoinPoint joinPoint, EventTracking eventTracking) throws Throwable {
        // 统计方法耗时
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        Object[] args = joinPoint.getArgs();
        long duration = System.currentTimeMillis() - begin;
        // 耗时：大于等于 1000ms 为 s 单位 ，小于 1000ms 还是为 ms 单位
        String timeConsuming = logExecutionTime(duration);
        if (args.length > 0 && args[0] instanceof Long) {
            SysEventTracking tracking = eventTrackingService.getEventTrackingByTablesId(eventTracking.tables(),String.valueOf(args[0]));
            if(null != tracking){
                tracking.setCount(1 + tracking.getCount());
                eventTrackingService.updateSysEventTracking(tracking);
            }else{
                SysEventTracking sysEventTracking = new SysEventTracking();
                sysEventTracking.setTablesId(String.valueOf(args[0]));
                sysEventTracking.setTables(eventTracking.tables());
                sysEventTracking.setCount(1L);
                sysEventTracking.setEvent(eventTracking.event());
                eventTrackingService.insertSysEventTracking(sysEventTracking);
            }
        }
        return result;
    }

    // 耗时单位
    private String logExecutionTime(long duration) {
        if (duration >= 1000) {
            double seconds = duration / 1000.0;
            return String.format("%.2f s", seconds);
        } else {
            return String.format("%d ms", duration);
        }
    }
}